package com.organization

class TreeService {

    def commonService

    //get branch from selected node
    def getBranch(nodeId){
        if (nodeId == commonService.rootNodeStr){
            return getTree()
        }
        else if (nodeId =~ commonService.depNodeStr){
            return getProjectsTreeByDep(commonService.nodeIdToDbId(nodeId))
        }
        else if (nodeId =~ commonService.projNodeStr){
            return getEmployeeTreeByProj(commonService.nodeIdToDbId(nodeId))
        }
        return [:]
    }

    //get branch for root node
    protected def getTree() {
		return Department.list().collect{[
			text : it.toString(),
			id   : (commonService.depNodeStr+it.id),
            children: getProjectsTreeByDep(it.id)
		]}	
	}

    //get brunch for department node
    protected def getProjectsTreeByDep(def depId){
		Department dep = Department.get(depId)
		return Project.findAllByDepartment(dep).collect{[
			text : it.toString(),
			id   : (commonService.projNodeStr+it.id),
            children : getEmployeeTreeByProj(it.id)
			]}
	}

    //get brunch for project node
    protected def getEmployeeTreeByProj(def projId){
		Project proj = Project.get(projId)
		return Employee.findAllByProject(proj).collect{[
			text : it.toString(),
			id   : (commonService.emplNodeStr+it.id),
            leaf : "true"
			]}
	}
}
